<!-- App.vue -->
<script setup lang="ts">
import {PlusLayout} from "plus-pro-components";
import {type RouteRecordRaw, useRoute} from "vue-router"; // 用于获取当前路由信息
import router from "./router";
import {computed, ref, toRaw} from "vue";
import {onMounted} from 'vue'
import {useAuthStore} from './stores/auth'
import {ElMessage} from 'element-plus';
import {useBrandsStore} from "./stores/brand.ts";
import {useSalesRepsStore} from "./stores/sales_rep.ts";

const authStore = useAuthStore()
const brandsStore = useBrandsStore()
const salesRepsStore = useSalesRepsStore()
const userInfo = computed(() => authStore.userInfo)
const brands = computed(() => brandsStore.brands)
const sales_reps = computed(() => salesRepsStore.sales_reps)

const user = ref({
  username: '',
  avatar: undefined,
})
const currentMode = import.meta.env.MODE;
const released = (currentMode === "production");
onMounted(() => {
  if (released && !!!authStore.isAuthenticated) {
    return;
  }
// 仅在登录状态有效时调用（路由守卫已确保 token 存在）
  if (!user.value.username) {
    authStore.fetchUserInfo();
    user.value.username = authStore.userInfo?.name;
  }

  if (!brands.value || brands.value.length === 0) {
    brandsStore.fetchBrands();
  }
  if (!sales_reps.value || sales_reps.value.length === 0) {
    salesRepsStore.fetchSalesReps();
  }
})

const handleLogout = () => {
  authStore.logout()
}
// 获取路由配置
const allRoutes = router.options.routes;
const routes = allRoutes.filter(r => !(r?.meta?.hidden)) as RouteRecordRaw[]
// 获取当前路由实例
const route = useRoute();

// 判断当前路由是否为登录页（不需要Layout的页面）
const isLoginPage = () => {
  // 这里的 '/login' 对应你的登录页路由路径，根据实际情况修改
  return route.path === "/login";
};
const handleClickDropdownItem = (item: { label: string; value: string }) => {
  if ('logout' === item.value) {
    handleLogout()
  }
  ElMessage.success(item.label)
}

const dropdownList = ref([
  {
    label: '设置',
    value: 'setting'
  },
  {
    label: '个人中心',
    value: 'userCenter'
  }
])

</script>

<template>
  <!-- 根据当前路由动态选择布局 -->
  <template v-if="isLoginPage()">
    <!-- 登录页：不使用PlusLayout，直接渲染路由内容 -->
    <router-view/>
  </template>
  <template v-else>
    <!-- 其他页：使用PlusLayout布局 -->
    <PlusLayout
        :sidebar-props="{ routes, collapse:true }"
        :header-props="{
          title: '幸福小站',
          logo: '/happy.svg',
          userInfo: user,
          onClickDropdownItem: handleClickDropdownItem,
          dropdownList: dropdownList
          }"
    >
      <router-view/>
    </PlusLayout>
  </template>
</template>

<style scoped>
/* 保持原样式，或根据需要调整 */
</style>